package com.k.activemq.amqp;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * 1. 使用 amqp client java
 * <dependency>
 * <groupId>com.rabbitmq</groupId>
 * <artifactId>amqp-client</artifactId>
 * <version>5.13.1</version>
 * </dependency>
 * <p>
 * 2. 连接发送消息
 * <p>
 * 3. broker: RabbitMq 默认协议 或 ActiveMQ - amqp协议
 */
public class AmqpPublisher1 {
    private static final String EXCHANGE_NAME = "TEST_EXCHANGE_LOG";

    public static void publish() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.110.12.159");
        factory.setUsername("admin");
        factory.setPassword("Command_123");
        factory.setPort(27000);
        factory.setVirtualHost("mcc_vhost_dev");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            // 开启发送确认模式
            channel.confirmSelect();

            // EXCHANGE 如果Broker中已经存在不需要声明
//            channel.exchangeDeclare(EXCHANGE_NAME, "topic");

            String routingKey = "log.xx";
            String message = "haha";

            channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");

            // 消息发送确认返回值
            channel.addConfirmListener(new ConfirmListener() {
                @Override
                public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                    System.out.println("已确认消息: deliveryTag:" + deliveryTag + " mutiple:" + multiple);
                }

                @Override
                public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                    System.out.println("未确认消息");
                }
            });
        }
    }

    public static void main(String[] args) {
        try {
            publish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
